import os
import sys
# 获取当前文件所在目录的父目录（项目根目录）
project_root = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, project_root)
import datetime
from core.global_text import g_varial
import allure
import jsonpath
import pytest
import logging
from extend.keywords import Keywords
keywords = Keywords()
@pytest.fixture(scope="session")
@allure.title("获取登录token")
def get_login_token():
    with allure.step("登录测试前数据准备"):
        login_url = "http://shop-xo.hctestedu.com/index.php?s=/api/user/login&application=app&application_client_type=weixin"
        # 请求参数
        login_data = {
            "accounts": "jeremy111",
            "pwd": "jeremy123",
            "type": "username"
        }
        request_data = {"url": login_url,"data": login_data}
    with allure.step("发送登录请求"):
        # 发POST登录请求
        # login_res = requests.request("POST", login_url, data=login_data)
        login_res = keywords.requests_post(**request_data)
    with allure.step("获取返回值"):
    # 拿到返回值，按json格式返回
        login_json = login_res.json()
    # print(login_json)
    with allure.step("断言msg"):
        exmsg = "登录成功"
        # sjmsg = jsonpath.jsonpath(login_json, "$.msg")[0]
        sjmsg = keywords.ex_jsonData(response=login_res,EXVALUE="$.msg",INDEX=0)
        keywords.assert_method(exmsg, sjmsg, "==")
    with allure.step(f"获取token值"):
        # 获取token
        # login_token = jsonpath.jsonpath(login_json, "$..token")[0]
        login_token = keywords.ex_jsonData(response=login_res, EXVALUE="$..token", INDEX=0,VARNAME="login_token")
        return login_token





@pytest.fixture(scope="session")
@allure.title("数据清洗")
def data_clean():
    """
    取消订单-删除订单-删除地址
    :return:
    """
    yield
    with allure.step("取消订单前准备"):
        login_token = g_varial().get_dic("login_token")
        order_id = g_varial().get_dic("order_id")
        cancel_order_url = f"http://shop-xo.hctestedu.com/index.php?s=/api/order/cancel&application=app&application_client_type=pc&token={login_token}"
        cancel_order_data = {"id":order_id}
        request_data = {"url":cancel_order_url, "json": cancel_order_data}
    with allure.step("发送取消订单请求"):
        cancel_order_res = keywords.requests_post(**request_data)
    with allure.step("返回结果"):
        cancel_order_json = cancel_order_res.json()
    with allure.step("提取返回结果的msg:取消成功"):
        cancel_order_msg = jsonpath.jsonpath(cancel_order_json, "$.msg")[0]
    with allure.step("断言返回的msg"):
        keywords.assert_method("取消成功", cancel_order_msg, "==")
    with allure.step("删除订单前准备"):
        login_token = g_varial().get_dic("login_token")
        order_id = g_varial().get_dic("order_id")
        delelte_order_url = f"http://shop-xo.hctestedu.com/index.php?s=/api/order/delete&application=app&application_client_type=pc&token={login_token}"
        delete_order_data = {"id":order_id}
        request_data = {"url":delelte_order_url, "json": delete_order_data}
    with allure.step("发送删除订单请求"):
        delete_order_res = keywords.requests_post(**request_data)
    with allure.step("返回结果"):
        delete_order_json = delete_order_res.json()
    with allure.step("提取返回结果的msg:删除成功"):
        cancel_order_msg = jsonpath.jsonpath(delete_order_json, "$.msg")[0]
    with allure.step("断言返回的msg"):
        keywords.assert_method("删除成功", cancel_order_msg, "==")
    with allure.step("删除地址前数据准备"):
        login_token = g_varial().get_dic("login_token")
        address_id = g_varial().get_dic("address_id")
        delete_address_url = f"http://shop-xo.hctestedu.com/index.php?s=/api/useraddress/delete&application=app&application_client_type=pc&token={login_token}"
        address_data = {"id":address_id}
        request_data = {"url":delete_address_url, "data": address_data}
    with allure.step("发送请求"):
        delete_address_res = keywords.requests_post(**request_data)
    with allure.step("得到返回结果"):
        delete_address_res_json = delete_address_res.json()
    with allure.step("提取删除地址成功的msg"):
        address_msg = jsonpath.jsonpath(delete_address_res_json, "$.msg")[0]
    with allure.step("断言删除地址返回的msg"):
        keywords.assert_method("删除成功", address_msg, "==")

# 对于给定的测试用例(item)和调用步骤(call)，返回一个测试报告对象(_pytest.runner.TestReport)
# 装饰的钩子函数，有以下两个作用：
#（1）可以获取到测试用例不同执行阶段的结果（setup，call，teardown）
#（2）可以获取钩子方法的调用结果（yield返回一个result对象）和调用结果的测试报告（返回一个report
# 对象）
@pytest.hookimpl(hookwrapper=True,tryfirst=True)
def pytest_runtest_makereport(item,call):
    # 通过 out = yield 定义了一个生成器。在生成器中，res = out.get_result() 获取了测试结果对象
    out = yield
    res = out.get_result()
    # res.when == "call"：表示正在运行调用测试函数的阶段。
    if res.when == "call":
        logging.info(f"用例ID：{res.nodeid}")
        logging.info(f"测试结果：{res.outcome}")
        logging.info(f"故障表示：{res.longrepr}")
        logging.info(f"异常：{call.excinfo}")
        logging.info(f"用例耗时：{res.duration}")
        logging.info("**************************************")


LOG_PATH='./log'
def pytest_configure(config):
    now = datetime.datetime.now() # 打印当前时间
    date_str = now.strftime("%Y-%m-%d_%H-%M-%S") # 格式
    # 文件名：每次都是以最新的时间命名文件 pytest_2025-xx-xx-xx.log
    log_file_name = f"pytest_{date_str}.log"
    # 文件路径 文件夹里面
    full_log_path = os.path.join(LOG_PATH, log_file_name)
    config.option.log_file=full_log_path # 将路径配置到pytest的log_file的目录下
    config.option.log_file_mode = "a" # 设置日志文件为追加模式